<template>
	<view class="dx-city-select">
		<el-cascader
			v-model="value"
			clearable
			:placeholder="level == 2 ? '请选择省/市/区' : level == 1 ? '请选择省/市' : '请选择省'"
			:props="cityProps"
			@change="change"
		>
		</el-cascader>
	</view>
</template>
<script setup lang="ts" name="DxCitySelect">
import { ref, watch } from 'vue';
import { axios } from '@/uni_modules/dx-admin/api/index';
import useElFormItem from '@/uni_modules/dx-admin/libs/useElFormItem';
import { CascaderProps } from 'element-plus';
const { emitTrigger } = useElFormItem();
const props = withDefaults(
	defineProps<{
		modelValue: any;
		url?: string;
		funcName?: string;
		level?: number;
		labelField?: string;
		valueField?: string;
		parentField?: string;
	}>(),
	{
		funcName: 'dx-func-admin',
		url: 'index/getCity',
		labelField: 'name',
		valueField: 'code',
		parentField: 'parent_code',
		level: 1,
	}
);
const value = ref([]);
// 绑定关系
const $emit = defineEmits(['update:modelValue']);
watch(
	() => props.modelValue,
	(newProps) => {
		value.value = newProps;
	}
);
function change(val: any) {
	$emit('update:modelValue', val);
	emitTrigger();
}
const cityProps = ref<CascaderProps>({
	lazy: true,
	expandTrigger: 'hover',
	hoverThreshold: 800,
	lazyLoad(node, resolve) {
		const { level = 0 } = node;
		axios
			.send(props.url, props.funcName, {
				[props.parentField]: node.value || '',
			})
			.then((res) => {
				if (res.code === 1000) {
					let data = res.data?.list !== void 0 ? res.data.list : res.data;
					data = data.map((item: { [x: string]: any; }) => {
						return {
							leaf: level >= props.level,
							label: item[props.labelField],
							value: item[props.valueField],
						};
					});
					resolve(data);
				} else {
					ElMessage.error(res.message);
				}
			});
	},
});
</script>
<style lang="scss" scoped>
.dx-city-select {
	width: 100%;
	::v-deep {
		.el-cascader {
			width: 100%;
		}
	}
}
</style>
